<?php
/**
 * 字段有:
 * 	id
 * 	from: 发送号码
 * 	to: 目标号码
 * 	content: 内容
 * 	sended: 发送时间
 * 	created: 入表时间
 */
//对{sms } ... {/sms }的解析
function smarty_block_sms (&$params, $content, &$smarty, &$repeat){
   return $smarty->callblockfunc($params,$content,$smarty,$repeat, getsms);
}

/**
 * 参数：
 * 	boy: 联系的一方
 * 	girl: 联系的另一方
 * 	
 * @param unknown_type $params
 */
function getsms(&$params) {
	global $_db,$cf_pagenum;
	
	//#region 构建sql
	$countsql = "select count(*) from t_sms t where 1=1 ";//获得条件约束下的结果集的所有行数，用于分页
	
	//获取可访问的字段列表
	$selectlist = getselectlist("sms");
	if(null==$selectlist) return null;
	
	$sql = "select $selectlist from t_sms t where 1=1 ";
	
	//条件处理
	$sqlwhere = "";
	if(array_key_exists("id", $params)) $sqlwhere .= " and t.c_id = '$params[id]' ";
	if(array_key_exists('boy', $params) && array_key_exists('girl', $params)){
		$sqlwhere .= " and ( 
			(t.c_from='$params[boy]' and t.c_to='$params[girl]') 
		or  (t.c_from='$params[girl]' and t.c_to='$params[boy]') )";
	}
	elseif(array_key_exists('boy', $params)){
		$sqlwhere .= " and ( 
			(t.c_from='$params[boy]') 
		or  (t.c_to='$params[boy]') )";
	}
	elseif(array_key_exists('girl', $params)){
		$sqlwhere .= " and ( 
			(t.c_from='$params[girl]') 
		or  (t.c_to='$params[girl]') )";
	}
	
	//排序处理
	$sqlorderby = "";
	$sqlorderby .= " order by t.sended asc ";

	//#region 分页处理
	$limit = "";
	if(!array_key_exists("pagenum", $params)){
		$params['pagenum'] = $cf_pagenum;
	}
	if(0>=$params['pagenum']){
		$params['pagenum'] = -1;
		$params['pageindex'] = 0;
	}
	else{
		$params['pageindex'] = !isset($params['pageindex'])?0:(int)$params['pageindex'];
		$start = $params['pageindex']*$params['pagenum'];
		$limit = " limit $start, $params[pagenum]";
	}
	//#endreg 分页处理
	
	//组装sql
	$countsql .= "$sqlwhere $sqlorderby";
	$sql .= "$sqlwhere $sqlorderby $limit";
	//#endreg 构建sql
	
	//获取结果集
	$totalcount = $_db->get1stcolval($countsql);
	$res = $_db->query($sql);
	
	//#region 分页结果
	if($params['pagenum']<=0){
		$params['pagenum'] = $totalcount;
	}
	else{
		$params['totalcount'] = $totalcount;//将总数放入params中以备分页所用
	}
	//#endreg 分页结果
	
	return $res;
}

/**
 * 将短信保存到数据库中
 * 
 * @param unknown_type $smses
 */
function insertsms($smses){
	global $_db;
	
	if(null==$smses || !is_array($smses)) return false;
	
	foreach ($smses as $sms){
		$sms['created'] = time();
		$_db->insert("sms", $sms);
	}
}
?>